package com.gem.controller;

import com.alibaba.druid.util.StringUtils;
import com.gem.domain.CampusVisit;
import com.gem.domain.User;
import com.gem.service.CampusVisitService;
import com.gem.service.UserService;
import com.gem.util.ExcelUtil;
import com.gem.util.MessageUtil;
import com.gem.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import static com.gem.util.ExcelUtil.setHSSFValidation;

/**
 * @Author: 玲
 * @Description:
 * @create 2019-10-21 9:30
 * @Modified By:
 */
@Controller
@SuppressWarnings("all")
public class CampusVisitController {

    @Autowired
    private CampusVisitService service;

    @Autowired
    private UserService userService;

    @RequestMapping("/campusVisit/findAll")
    public String findAll(Model model, HttpSession session,
                          @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                          @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            User user = (User) session.getAttribute("user");

            List<User> users = userService.findMmembers();
            model.addAttribute("users", users);
            CampusVisit campusVisit = new CampusVisit();
            campusVisit.setPersonname(user.getPersonname());
            PageInfo<CampusVisit> pageBeans = null;
            if (user.getAuthority() == 1) {
                pageBeans = service.findAll(currentPage, pageSize);
            } else {
                pageBeans = service.search(campusVisit, currentPage, pageSize);
            }
            if (pageBeans != null && pageBeans.getList().size() > 0) {
                model.addAttribute("pageBean", pageBeans);
                List<Integer> pageValue = PageUtil.getPageValue(pageBeans.getPages(), currentPage);
                model.addAttribute("pageValue", pageValue);
            } else {
                System.out.println();
                model.addAttribute("info", "没有数据请先添加！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/", "服务器异常！请联系管理员！", model);
            return "message";
        }
        return "campus/visit";
    }

    @RequestMapping("/campusVisit/deleteById")
    @ResponseBody
    public String delete(Integer campusVisitId, int currentPageSize, int currentPage, int lastPage) {
        try {
            if (service.deleteById(campusVisitId) > 0) {
                if (currentPageSize == 1 && currentPage == lastPage) {
                    return "0";
                }
            }
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
    }

    @RequestMapping("/campusVisit/deleteAll")
    public String deleteAll(int[] campusVisitIds, Model model) {
        try {
            if (campusVisitIds != null && campusVisitIds.length != 0) {
                service.deleteAll(campusVisitIds);
                MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "删除成功！", model);
            } else {
                MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "没有参数传递", model);
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "服务器异常！请联系管理员！", model);
        }
        return "message";
//        return "redirect:/campusVisit/findAll";
    }

    @RequestMapping("/campusVisit/saveUI")
    public String saveUI(Model model) {
        try {
            List<User> users = userService.findMmembers();
            model.addAttribute("users", users);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "服务器异常！请联系管理员！", model);
            return "message";
        }
        return "campus/visit_insert";
    }

    @RequestMapping("/campusVisit/save")
    public String save(CampusVisit campusVisit, Model model) {
        try {
            service.save(campusVisit);
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "添加成功！", model);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "服务器异常！请联系管理员！", model);
        }
        return "message";
    }

    @RequestMapping("/campusVisit/updateUI")
    public String updateUI(Model model, Integer campusVisitId,
                           @RequestParam(value = "currentPage") int currentPage,
                           @RequestParam(value = "pageSize") int pageSize) {
        try {
            List<User> users = userService.findMmembers();
            model.addAttribute("users", users);
            CampusVisit campusVisit = service.findById(campusVisitId);
            model.addAttribute("campusVisit", campusVisit);
            model.addAttribute("currentPage", currentPage);
            model.addAttribute("pageSize", pageSize);
            User one = userService.findById(campusVisit.getCampusGemPerson());
            model.addAttribute("one", one);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll", "服务器异常！请联系管理员！", model);
        }
        return "campus/visit_update";

    }

    @RequestMapping("/campusVisit/update")
    public String update(CampusVisit campusVisit, Model model,
                         @RequestParam(value = "currentPage") String currentPage,
                         @RequestParam(value = "pageSize", defaultValue = "5") String pageSize) {
        try {
            if (service.update(campusVisit) == 1) {
                MessageUtil.returnInfoPage("3", "/campusVisit/findAll?currentPage= " + currentPage + "&pageSize=" + pageSize, "修改成功！", model);
            } else {
                MessageUtil.returnInfoPage("3", "/campusVisit/findAll?currentPage= " + currentPage + "&pageSize=" + pageSize, "未作修改！", model);
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll?currentPage=" + currentPage + "&pageSize=" + pageSize, "服务器异常！请联系管理员！", model);
        }
        return "message";
    }

    @RequestMapping("/campusVisit/search")
    public String search(CampusVisit campusVisit, Model model,
                         @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                         @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {

        try {
            String campusName = campusVisit.getCampusName();
            String personname = campusVisit.getPersonname();
            PageInfo<CampusVisit> pageBeans = service.search(campusVisit, currentPage, pageSize);
            if (pageBeans != null && pageBeans.getList().size() > 0) {
                model.addAttribute("pageBean", pageBeans);
                List<Integer> pageValue = PageUtil.getPageValue(pageBeans.getPages(), currentPage);
                model.addAttribute("pageValue", pageValue);
                model.addAttribute("searchUrl", "/campusVisit/search");
                model.addAttribute("campusName", campusName);
                model.addAttribute("personname", personname);
//                model.addAttribute("campusVisit", campusVisit);
            } else {
                model.addAttribute("info", "没有数据请先添加！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campusVisit/findAll?currentPage=" + currentPage + "&pageSize=" + pageSize, "服务器异常！请联系管理员！", model);
            return "message";
        }
        return "campus/visit";
    }

    //导出excel模板
    @RequestMapping("/campusVisit/exportTemplate")
    public void exportExcelTemplate(HttpServletResponse response, HttpSession session) throws Exception {
        //创建excel工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建sheet对象
        HSSFSheet sheet = workbook.createSheet("院校拜访记录");

        //创建水平垂直居中的cellStyle单元格样式对象
        HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

        //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
        HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

        //模板第一行例子展示
        HSSFCellStyle rowStyle = ExcelUtil.getExamplStyle(workbook);

        // 单元格类型日期格式化
        HSSFCellStyle cellStyleDate = ExcelUtil.getDateRedStyle(workbook);

        //创建行对象
        HSSFRow row = null;

        // 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue("院校拜访记录表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        //第二行的单元格进行合并,语句提示
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 12));
        row = sheet.createRow(1);
        HSSFCell beginCell1 = row.createCell(0);
        beginCell1.setCellValue("请按照模板字段和单元格格式提交数据,日期类型请使用给定格式刷刷一下");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell1.setCellStyle(cellStyle);

        //次数写表头,根据各个页面的进行修改
        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("院校名称");
        headRow.createCell(1).setCellValue("交往日期");
        headRow.createCell(2).setCellValue("交往方式");
        headRow.createCell(3).setCellValue("院方人员");
        headRow.createCell(4).setCellValue("我方人员");
        headRow.createCell(5).setCellValue("洽谈事件/内容");
        headRow.createCell(6).setCellValue("备注");
        headRow.setHeightInPoints(25); // 设置行的高度
        for (int i = 0; i < 7; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }

        //下拉列表的参数--渠道专员（市场）
        User user = (User) session.getAttribute("user");
        String[] personName = {user.getPersonname()};
        //设置当前工作表的设么地方需要下拉,需要自己对着表格设置位置,没有就不需要写
        sheet = setHSSFValidation(sheet, personName, 3, 10000, 4, 4);

        String[] visitWay = {"我方上门", "电话沟通", "邮件", "微信QQ沟通", "其他"};
        sheet = setHSSFValidation(sheet, visitWay, 3, 10000, 2, 2);
        //优化 降低冗余
        HSSFCell cell = null;

        //设置所有列列宽
        for (int i = 0; i < 7; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度

        //在第四行给一行数据模板,根据对应表的对应字段填写

        row = sheet.createRow(3);

        //第一列,名字
        cell = row.createCell(0);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("院校名称");

        cell = row.createCell(1);
        cell.setCellStyle(cellStyleDate);//改单元格为日期样式
        cell.setCellValue(new Date());//赋值

        cell = row.createCell(2);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("我方上门");

        cell = row.createCell(3);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("院方人员1");

        cell = row.createCell(4);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("市场员工1");

        cell = row.createCell(5);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("洽谈事件/内容");

        cell = row.createCell(6);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("没啥备注");

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=template.xls");

        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    //导出excel
    @RequestMapping("/campusVisit/export")
    public void exportExcel(HttpServletResponse response) throws Exception {
        //创建excel工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建sheet对象
        HSSFSheet sheet = workbook.createSheet("院校拜访记录");

        //创建水平垂直居中的cellStyle单元格样式对象
        HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

        //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
        HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

        // 单元格类型日期格式化
        HSSFCellStyle cellStyleDate = ExcelUtil.getDateStyle(workbook);

        //创建行对象
        HSSFRow row = null;
        // 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue("院校拜访记录表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        //第二行的单元格进行合并,语句提示
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 10));
        row = sheet.createRow(1);
        HSSFCell beginCell1 = row.createCell(0);
        beginCell1.setCellValue("请按照模板字段和单元格格式提交数据,日期类型请使用给定格式刷刷一下");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell1.setCellStyle(cellStyle);

        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("院校名称");
        headRow.createCell(1).setCellValue("交往日期");
        headRow.createCell(2).setCellValue("交往方式");
        headRow.createCell(3).setCellValue("院方人员");
        headRow.createCell(4).setCellValue("我方人员");
        headRow.createCell(5).setCellValue("洽谈事件/内容");
        headRow.createCell(6).setCellValue("备注");
        headRow.setHeightInPoints(25); // 设置行的高度
        for (int i = 0; i < 7; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }

        //创建水平垂直居中加粗的cellStyle单元格样式,给数据试用
        HSSFCellStyle rowStyle = ExcelUtil.getCenterStyle(workbook);

        //调用service方法查询所有数据集合
        List<CampusVisit> visitList = service.findAllCampusVisit();
        //优化 降低冗余
        HSSFCell cell = null;
        CampusVisit visit = null;
        //设置所有列列宽
        for (int i = 0; i < 7; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度

        for (int i = 0; i < visitList.size(); i++) {
            row = sheet.createRow(i + 3);
            visit = visitList.get(i);
            //第一列 院校名称
            // 数字类型 需要加一个数字类型指定参数
//            row.createCell(0, CellType.NUMERIC).setCellValue(visit.getCaName());
            cell = row.createCell(0);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(visit.getCampusName());
            //第二列 交往日期
            cell = row.createCell(1);
            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
            cell.setCellValue(visit.getCampusVisitDate());//赋值
            //第三列 交往方式
            cell = row.createCell(2);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(visit.getCampusVisitWay());
            //第四列 院方人员
            cell = row.createCell(3);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(visit.getCampusPerson());
            //第五列 我方人员
            cell = row.createCell(4);
            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
            cell.setCellValue(visit.getPersonname());//赋值
            //第六列 洽谈事件/内容
            cell = row.createCell(5);
            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
            cell.setCellValue(visit.getCampusVisitInfo());//赋值
            //第七列 备注
            cell = row.createCell(6);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(visit.getCampusVisitRemarks());
        }

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=CampusVisit.xls");

        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();


    }

    //导入excel
    @RequestMapping("/campusVisit/import")
    @ResponseBody
    @Transactional
    public String importExcel(@RequestParam("file") MultipartFile file, Model model) {
        try {
            //固定格式  参数file 为 文件上传的input的name
            HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();

            CampusVisit visit = null;
            HSSFRow row = null;

            //从第四行开始读取数据
            for (int i = 3; i <= lastRowNum; i++) {
                visit = new CampusVisit();
                row = sheet.getRow(i);

                if (StringUtils.isEmpty(row.getCell(0).getStringCellValue()) && StringUtils.isEmpty(row.getCell(1).getStringCellValue())) {
                    break;//如果是空行无数据，停止写入
                }
                visit.setCampusName(row.getCell(0).getStringCellValue());

                Date dsDate = row.getCell(1).getDateCellValue();
                visit.setCampusVisitDate(dsDate);

                visit.setCampusVisitWay(row.getCell(2).getStringCellValue());

                visit.setCampusPerson(row.getCell(3).getStringCellValue());
                //查询我方人员的uid
                User user = userService.findByName(row.getCell(4).getStringCellValue());
                visit.setCampusGemPerson(user.getUid());

                visit.setCampusVisitInfo(row.getCell(5).getStringCellValue());

                visit.setCampusVisitRemarks(row.getCell(6).getStringCellValue());
                //添加一个对象,循环,直到结束
                service.save(visit);
            }
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "-1";
        }
    }

}
